<!--
 * @Author: Bennty
 * @Date: 2024-07-08 09:11:36
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-09-19 17:57:43
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item label="模糊搜索" prop="customerName">
                        <el-input v-model="queryParams.customerName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="业务员" prop="personName">
                        <!-- <el-input v-model="queryParams.name" placeholder="请输入业务员名称" clearable @keyup.enter="handleQuery" /> -->
                        <el-select v-model="queryParams.personName" placeholder="请输入业务员名称" clearable filterable >
                            <el-option v-for="user in roleKeyUserList" :key="user.userId" :label="user.userName" :value="user.userName"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleClickAdd">新增</el-button>
                    </el-col>
                </el-row>
            </template>
            <el-table v-loading="tableLoading" ref="multipleTableRef" :data="customerList" highlight-current-row >
                <el-table-column label="未交易时间" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.dealStatus == '0'" :class="scope.row.dealStatus !== '0'?'status completed':'status uncompleted'">{{'从未成交' }}</span>
                        <span v-else class="status completed">{{ `${scope.row.dealIntervalDays}天` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户" prop="customerName" align="center" width="160"></el-table-column>
                <el-table-column label="业务员" prop="personName" align="center"></el-table-column>
                <el-table-column label="下次联系时间" prop="nextContactDate" align="center"></el-table-column>
                <el-table-column label="客户级别" align="center">
                    <template #default="scope">
                        <span class="level-one" v-if="scope.row.customerLevel == '1'">一级客户</span>
                        <span class="level-two" v-else-if="scope.row.customerLevel == '2'">二级客户</span>
                        <span class="level-three" v-else-if="scope.row.customerLevel == '3'">三级客户</span>
                        <span class="level-four" v-else-if="scope.row.customerLevel == '4'">四级客户</span>
                        <span class="level-five" v-else-if="scope.row.customerLevel == '5'">五级客户</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户来源" align="center" width="150">
                    <template #default="scope">
                        <span>
                            {{ customer_source.filter((item:any)=>item.value == scope.row.customerSource)[0]?.label }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="地址信息" align="center" width="180">
                    <template #default="scope">
                        <span>{{ scope.row.province + '/' + scope.row.city + '/' + scope.row.county }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="预付款余额" align="center">
                    <template #default="scope">
                        <span>{{ `￥${scope.row.prePayment}` }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="最后跟进时间" prop="finalFollowDate" align="center"></el-table-column>
                <el-table-column label="申请福利"  align="center">
                    <template #default="scope">
                        <span class="apply" v-if="scope.row.welfareStatus == '0'">未申请</span>
                        <span class="applying" v-else-if="scope.row.welfareStatus == '1'">申请中</span>
                        <span class="welfare-passed" v-else-if="scope.row.welfareStatus == '2'">已通过</span>
                        <span class="welfare-rejected" v-else-if="scope.row.welfareStatus == '3'">已拒绝</span>
                    </template>
                </el-table-column>
                <el-table-column label="样品信息">
                    <template #default="scope">
                        <el-button type="primary" link @click="handleCheckSimpleDetail(scope.row)">样品详情</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="190" align="center">
                    <template #default="scope">
                        <div class="operation">
                            <el-tooltip content="编辑" placement="top">
                                <el-button link type="success" :style="{fontSize:'16px'}"  icon="Edit" @click="handleClickEdit(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="删除" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="Delete" @click="handleClickDelete(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="分配客户" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="Download" @click="handleClickDistribute(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="查看跟进记录" placement="top">
                                <el-button link type="primary" :style="{fontSize:'16px'}"  icon="User" @click="handleClickFollowRecord(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="查看备注" placement="top">
                                <el-button link type="success" :style="{fontSize:'16px'}"  icon="Warning" @click="handleClickCheckRemark(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="转公海" placement="top">
                                <el-button link type="warning" :style="{fontSize:'16px',margin:'0'}"  icon="Drizzling" @click="handleClickToSea(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="结算方式" placement="top">
                                <el-button link type="danger" :style="{fontSize:'16px'}"  icon="CreditCard" @click="handleClickSettlement(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="申请福利" placement="top">
                                <el-button link type="info" :style="{fontSize:'16px'}"  icon="Ticket" @click="handleClickApplyWelfare(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="预付款退款申请" placement="top">
                                <el-button link type="primary" :style="{fontSize:'16px'}"  icon="Wallet" @click="handleClickRefund(scope.row)"></el-button>
                            </el-tooltip>
                            <el-tooltip content="样品申请" placement="top">
                                <el-button link type="success" :style="{fontSize:'16px'}"  icon="KnifeFork" @click="handleClickApplySimple(scope.row)"></el-button>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="标注" align="center">
                    <template #default="scope">
                        <el-button v-if="scope.row.signFlag == '1'" link icon="StarFilled" :style="{color:'orange',fontSize:'30px'}" @click="handleUpdateSignFlag(scope.row)"></el-button>
                        <el-button v-else link icon="Star" :style="{fontSize:'30px'}" @click="handleUpdateSignFlag(scope.row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getCustomers" />
        </el-card>
        <addCustomer :visible="addVisible" :sources="customer_source" @close="handleCancelAdd" @submit="handleSubmitAdd"/>
        <editCustomer :visible="editVisible" :sources="customer_source" :editId="editData" @close="handleCancelEdit" @submit="handleSubmitEdit" />
        <distribution :visible="distributionVisible" :data="distributionData" :users="roleKeyUserList" @submit="handleSubmitDistribute" @close="handleCancelDistribute"/>
        <checkRemark :visible="checkRemarkVisible" :data="checkRemarkData" @close="handleCloseCheckRemark"/>
        <settlementMehtod :visible="settlementMethodVisible" :data="settlementMethodData" :settlement="settlement_type" @close="handleCloseSettlement" @submit="handleSubmitSettlement" />
        <applyWelfare :visible="applyWelfareVisible" :data="applyWelfareData" :welfares="welfareList" @submit="handleSubmitApplyWelfare" @close="handleCancelApplyWelfare"/>
        <refund :visible="refundVisible" :data="refundData" @close="handleCancelRefund"/>
        <applySimple :visible="applySimpleVisible" :data="applySimpleData" :sources="customer_source" @close="handleCancelApplySimple" />
        <simpleDetail :visible="simpleDetailsVisible" :data="checkedId" @close="handleCancelSimpleDetail" />
        <toSea :visible="toSeaVisible" :data="toSeaData" :reason="to_sea_reason" @close="handleCloseToSea" @submit="handleSubmitToSea"/>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance,ElMessage,ElTable } from 'element-plus';
import { CustomerVO } from '@/api/sj/customer-crm/types';
import useCRMStore from '@/store/modules/crm';
import addCustomer from './components/addCustomer.vue';
import editCustomer from './components/editCustomer.vue';
import distribution from './components/distribution.vue';
import checkRemark from './components/checkRemark.vue';
import settlementMehtod from './components/settlementMehtod.vue';
import applyWelfare from './components/applyWelfare.vue';
import refund from './components/refund.vue';
import applySimple from './components/applySimple.vue';
import simpleDetail from './components/simpleDetail.vue';
import toSea from './components/toSea.vue';
import { getCustomerApi, updateSignFlagApi, deleteCustomerByIdApi, updateBecomePublicApi } from '@/api/sj/customer-crm/index';
import { getWelfareByLevelApi } from '@/api/sj/welfareExamine-crm/index';

const queryFormRef = ref<FormInstance>();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const totalData = ref(0);
const tableLoading = ref(false);
const customerList = ref<CustomerVO[]>([]);
const addVisible = ref(false);
const editVisible = ref(false);
const editData = ref<CustomerVO>();
const distributionVisible = ref(false);
const distributionData = ref<CustomerVO>();
const checkedRecordData = ref<CustomerVO>();
const { getUserListByRoleKey } = useCRMStore();
const { roleKeyUserList } = toRefs(useCRMStore());
const checkRemarkVisible = ref(false);
const checkRemarkData = ref<CustomerVO>();
const settlementMethodVisible = ref(false);
const settlementMethodData = ref<CustomerVO>();
const applyWelfareVisible = ref(false);
const applyWelfareData = ref<CustomerVO>();
const refundVisible = ref(false);
const refundData = ref<CustomerVO>();
const applySimpleVisible = ref(false);
const applySimpleData =ref<CustomerVO>();
const simpleDetailsVisible = ref(false);
const checkedId = ref<any>();
const toSeaVisible = ref(false);
const toSeaData = ref<CustomerVO>()
const router = useRouter();
const welfareList = ref<any[]>([]);


const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { customer_source,settlement_type, to_sea_reason } = toRefs<any>(proxy?.useDict('customer_source','settlement_type','to_sea_reason'));

const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: undefined,
        personName: undefined
    },
});
const { queryParams } = toRefs(data);


/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getCustomers();
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

const getCustomers = async ()=>{
    tableLoading.value = true;
    const { rows,total } = await getCustomerApi(queryParams.value);
    customerList.value = rows;
    totalData.value = total;
    tableLoading.value = false;
};

/**点击标识按钮 */
const handleUpdateSignFlag = async (row:CustomerVO) => {
    let updateData = {
        id: row.id,
        signFlag: row.signFlag == '0'? '1':'0'
    };
    await updateSignFlagApi(updateData).then((result)=>{
        if(result.code == 200){
            getCustomers();
        }
    });
};

/** 点击新增按钮 */
const handleClickAdd = ()=>{
    addVisible.value = true;
};

/** 取消新增 */
const handleCancelAdd = ()=>{
    addVisible.value = false;
};

/** 提交新增 */
const handleSubmitAdd = (result:any)=>{
    if(result){
        getCustomers()
    }
};

/** 点击编辑按钮 */
const handleClickEdit = (row:CustomerVO)=>{
    editVisible.value = true;
    editData.value = row;
};

/** 提交编辑 */
const handleSubmitEdit = (result:any) => {
    if(result){
        getCustomers();
    };
};

/** 取消编辑 */
const handleCancelEdit = ()=>{
    editVisible.value = false;
};

/**点击删除 */
const handleClickDelete = async (row:CustomerVO)=>{
    const _ids = row.id;
    const params = {
        id: _ids
    };
    await proxy?.$modal.confirm('确认删除客户?');
    await deleteCustomerByIdApi(params);
    proxy?.$modal.msgSuccess("删除成功");
    getCustomers();
};

/** 分配 */
const handleClickDistribute = (row:CustomerVO)=>{
    distributionVisible.value = true;
    distributionData.value = row;
};

/** 取消分配 */
const handleCancelDistribute = ()=>{
    distributionVisible.value = false;
};

/** 提交分配 */
const handleSubmitDistribute = (result: boolean)=>{
    if(result){
        getCustomers();
    }
}

/** 查看跟进记录 */
const handleClickFollowRecord = (row:CustomerVO)=>{
    router.push(`/guide/followRecord/${row.id}`);
    checkedRecordData.value = row;
};

/**查看备注 */
const handleClickCheckRemark =  (row:CustomerVO)=>{
    checkRemarkVisible.value = true;
    checkRemarkData.value = row;
};

/** 关闭查看备注 */
const handleCloseCheckRemark = ()=>{
    checkRemarkVisible.value = false;
};

/** 转公海 */
const handleClickToSea = (row: CustomerVO)=>{
    toSeaVisible.value = true;
    toSeaData.value = row;
};

const handleSubmitToSea = (result:boolean)=>{
    if(result){
        getCustomers();
    }
}

/** 关闭转公海 */
const handleCloseToSea = ()=>{
    toSeaVisible.value = false;
};

/** 查看支付方式 */
const handleClickSettlement = (row:CustomerVO)=>{
    settlementMethodVisible.value = true;
    settlementMethodData.value = row;
};

/** 关闭查看支付方式 */
const handleCloseSettlement = ()=>{
    settlementMethodVisible.value = false;
};

const handleSubmitSettlement = (result: boolean) => {
    if(result){
        getCustomers();
    };
};

/** 点击申请福利 */
const handleClickApplyWelfare = async (row:CustomerVO)=>{
    const { code,data } = await getWelfareByLevelApi(row.customerLevel)
    // console.log(row);
    if(code == 200){
        welfareList.value = data;
        applyWelfareVisible.value = true;
        applyWelfareData.value = row;
    };
};

const handleSubmitApplyWelfare = (result: boolean)=>{
    if(result){
        getCustomers();
    };
};

/** 关闭申请福利  */
const handleCancelApplyWelfare = ()=>{
    applyWelfareVisible.value = false;
};

/** 点击预付款退款申请 */
const handleClickRefund = (row:CustomerVO)=>{
    refundVisible.value = true;
    refundData.value = row;
};

/** 关闭预付款退款申请 */
const handleCancelRefund = ()=>{
    refundVisible.value = false;
};

/** 点击申请样品 */
const handleClickApplySimple = (row:CustomerVO)=>{
    applySimpleVisible.value = true;
    applySimpleData.value = row;
};

/** 点击关闭申请样品 */
const handleCancelApplySimple = (row: CustomerVO)=>{
    applySimpleVisible.value = false;
};

const handleSubmitApplySimple = () => {

};

/** 点击查看样品详情 */
const handleCheckSimpleDetail = (row:CustomerVO)=>{
    checkedId.value = row.id;
    simpleDetailsVisible.value = true;
};

/** 点击关闭查看样品详情 */
const handleCancelSimpleDetail = ()=>{
    simpleDetailsVisible.value = false;
};

onMounted(()=>{
    getCustomers();
    getUserListByRoleKey('business_role');
});

</script>

<style scoped lang="scss">
.status{
    line-height: 13;
}
.completed{
    color: yellowgreen
}
.uncompleted{
    color: orange
}
.level-one,.level-two {
    color:yellowgreen
}
.level-three,.level-four{
    color: orange;
}
.level-five{
    color: red
}
.mark{
    cursor: pointer;
}

.apply{
    color: skyblue
}

.applying{
    color: orange;
}

.welfare-passed{
    color: yellowgreen;
}

.welfare-rejected{
    color: red;
}

.operation{
    display: flex;
    flex-wrap: wrap;
}

</style>